<?php

namespace App\Http\Controllers\Dash;

use App\Http\Controllers\Controller;
use App\Model\Tutorial;
use App\User;
use Illuminate\Http\Request;

class TutorialController extends Controller
{
    //
    public function Index()
    {

        $tutorials = Tutorial::all();
        return view('dash.tutorial.index', compact('tutorials'));
    }

    public function create()
    {
        return view('dash.tutorial.create');
    }

    public function edit($id)
    {
        $data = Tutorial::find($id);
        return view('dash.tutorial.edit', compact('data', 'id'));
    }


    public function store(Request $request)
    {
        $re = new Tutorial();
        $re->title = $request->title;
        $re->text = $request->text;
        $re->save();
        return redirect(route('dash.tutorial'));
    }

    public function update($id, Request $request)
    {
        $re = Tutorial::find($id);
        $re->title = $request->title;
        $re->text = $request->text;
        $re->save();
        return redirect(route('dash.tutorial'));
    }

    public function delete($id)
    {
        $re = Tutorial::find($id)->delete();
        return redirect(route('dash.tutorial'))->with('success', $re);
    }

    public function upload(Request $request)
    {
        if ($request->hasFile('upload')) {
            //get filename with extension
            $filenamewithextension = $request->file('upload')->getClientOriginalName();

            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);

            //get file extension
            $extension = $request->file('upload')->getClientOriginalExtension();

            //filename to store
            $filenametostore = $filename . '_' . time() . '.' . $extension;

            //Upload File
            $request->file('upload')->storeAs('public/uploads', $filenametostore);

            $CKEditorFuncNum = $request->input('CKEditorFuncNum');
            $url = asset('storage/uploads/' . $filenametostore);
            $msg = 'Image successfully uploaded';
            $re = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";

            // Render HTML output
            @header('Content-type: text/html; charset=utf-8');
            echo $re;
        }
    }
}
